<?php
/**
 * Created by PhpStorm
 * User: honglin
 * Date: 2022/8/5
 * Time: 下午2:05
 */

namespace App\Service\System;




use App\Dao\System\SystemConfigDao;

use App\Dao\System\SystemConfigValueDao;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Collection;
use PharIo\Version\Exception;

class SystemConfigService
{
    /**
     * @Inject()
     * @var SystemConfigDao
     */
    protected $systemConfigDao;

    /**
     * @Inject()
     * @var SystemConfigValueDao
     */
    protected $systemConfigValueDao;


    public function lists($params)
    {
        $data = $this->systemConfigDao->getList();
        return $data;
    }

    public function add(Collection $params)
    {
        Db::beginTransaction();
        try{
            //判断是否存在key
            $this->systemConfigDao->existsKey($params->get('key')) && _Exception('systemConfig key已经存在');
            $this->systemConfigValueDao->existsKey($params->get('key')) && _Exception('systemConfigValue key已经存在');
            $this->systemConfigDao->create($params->toArray());
            $this->systemConfigValueDao->addDefaultValue($params->get('key'),$params->get('type'));
        }catch (\Exception $exception){
            Db::rollBack();
            _Error($exception->getMessage());
        }
        Db::commit();
        return true;
    }

    public function edit($configId, Collection $params)
    {
        $systemConfig = $this->systemConfigDao->where('config_id',$configId)->firstOrError();
        $systemConfig->fill($params->toArray());
        return $systemConfig->save();
    }
}